/**
 * jquery.dayhrPaginator.js 文档地址<http://git.oschina.net/zhqiok/dayhrPlugins/tree/master/PluginsDemos/dayhrPaginator?dir=1&filepath=PluginsDemos%2FdayhrPaginator&oid=c97f47ed214621dea32367db0eb99a46402ada16&sha=3c533728fa353fc8b7c3c0d489542d6846e5e8a3>
 * 版本号: 1.0
 * 作者：zackey
 * 创建时间: 2015/09/11
 * @options 类型 Object
 * @options.url 类型：String 请求数据的接口地址 必传
 * @options.limitList 类型：Array 每页多少条待选 非必传 默认 [10, 20, 50, 100]
 * @options.defaultLimit 类型：Int 每页默认多少条 非必传 默认20
 * @options.isShowPageNum 类型：Boolean 是否显示详细分页码 非必传 默认否
 * @options.isShowPageGoto 类型：Boolean 是否显示输入跳转 非必传 默认是
 * @optins.beforeSend 类型：function 翻页请求发送前的回调 非必传
 * @optins.complete 类型：function 翻页请求发送完成的回调 非必传
 * @optins.success 类型：function 翻页请求成功返回值的回调 非必传
 * 调用说明：
 */
define(function(require, exports,module) {
    require("commonStaticDirectory/plugins/dayhrPaginator/jquery.dayhrPaginator.css"); //翻页默认样式
    var Ajax = require("commonStaticDirectory/plugins/ajax.js");

    ;
    (function ($) {
        var DayhrPaginator = function (element, options) {
            this.$el = $(element);
            this.init(options);
        };
        DayhrPaginator.prototype = {
            constructor: DayhrPaginator
            , oDefaultOptions: {
                limitList: [10, 20, 50, 100]
                , defaultLimit: 20
                , totalCountLabel: '共<span>{0}</span>条记录'
                , limitLabel: '每页{0}条'
                , positionCountLabel: '{0}/{1}'
                , isShowPageNum: false  //是否显示详细分页码
                , isShowPageGoto: true //是否显示输入跳转
                , params: {} //附加参数传递后端
            }
            , init: function (options) {
                this.options = $.extend(true, {}, this.oDefaultOptions, options);
                this._initLayout();
                /*this.getData({
                 pageNo:1
                 ,pageSize:this.options.defaultLimit
                 });*/
            }
            /**
             * 渲染骨架
             **/
            , _initLayout: function () {
                var t = this;
                var $el = t.$el;
                var opts = t.options;
                var pgHtmls = [
                    //右边
                    '<div class="pageListRight">' +
                    '   <ul class="pageList"></ul><li class="positionCountLabel"></li>' +
                    '</div>',
                    '<div class="page_goto"><input class="page_goto_text" type="text" /><input class="page_goto_button" type="button" value="跳转"/></div>' +
                    '<div class="pageSelectLimitWrap" style="' + (opts.isShowSelectLimit ? '' : 'display:none') + '"><span class="pageSelectLimitTotal"></span><span>每页条数：</span><div class="pageSelectLimit"><input type="text" class="pageSelectLimit_input" value="20" readonly /><span class="pageSelectLimit_icon">∨</span><ul class="pageSelectLimit_ul"></ul></div></div>'
                ];
                $el.html($(pgHtmls.join('')));

                $el.addClass("dayhrPaginator"); //加上统一的class便于加样式

                this.$positionCountLabel = $el.find('.positionCountLabel');
                this.$pageList = $el.find('.pageList');
                this.$pageSelectLimitWrap = $el.find(".pageSelectLimitWrap"); //下拉选择每页条数
                //下拉每页多少条
                $.each(opts.limitList, function () {
                    var sDefaultLimit = (opts.defaultLimit && opts.defaultLimit == this) ? 'class="limitSelected"' : '';
                    var $optionSelect = $('<li ' + sDefaultLimit + '>' + this + '</li>'); //下拉的
                    t.$pageSelectLimitWrap.find(".pageSelectLimit_ul").append($optionSelect); //下拉的
                });


                //跳转翻页
                $el.find(".page_goto")[opts.isShowPageGoto ? "show" : "hide"](); //是否显示翻页跳转
                var $text = $el.find(".page_goto_text");
                var $btngo = $el.find(".page_goto_button");

                function gotoPage(page) {
                    if (page > parseInt(t.totalPage) || page < 1) {
                        return false;
                    }
                    // 跳转页
                    //$el.data('page', page);
                    t.page = page;
                    //t.$mmGrid.load();
                    t.getData({pageNo: page});
                }

                $btngo.on("click", function () {
                    if ($.trim($text.val())) {
                        gotoPage(parseInt($.trim($text.val())));
                    }
                });
                $text.on("keyup", function (e) {
                    if (e.keyCode == 13 && $.trim($text.val())) {
                        gotoPage(parseInt($.trim($text.val())));
                    }
                });

                //下拉选择每页条数的控件
                t.$pageSelectLimitWrap.on("click", ".pageSelectLimit_input,.pageSelectLimit_icon", function (event) {
                    var _$ul = $(this).parent().find(".pageSelectLimit_ul");
                    if (_$ul.is(":hidden")) {
                        _$ul.show();
                        t.$pageSelectLimitWrap.find(".pageSelectLimit_icon").css({transform: "rotate(540deg)"});
                    } else {
                        _$ul.hide();
                        t.$pageSelectLimitWrap.find(".pageSelectLimit_icon").css({transform: "rotate(0deg)"});
                    }
                    event.stopPropagation();
                });
                t.$pageSelectLimitWrap.on("click", "li", function () {
                    $(this).addClass("limitSelected").siblings().removeClass("limitSelected");
                    $(this).parent().hide();
                    t.$pageSelectLimitWrap.find(".pageSelectLimit_icon").css({transform: "rotate(0deg)"});
                    t.$pageSelectLimitWrap.find("input.pageSelectLimit_input").val($(this).text());
                    //t.$mmGrid.load();  //重载表格数据
                    t.getData({pageSize: $(this).text()});
                });
                $(document).on("click", function (event) {
                    if (!$(event.target).parents(".pageSelectLimit").length) {
                        t.$pageSelectLimitWrap.find(".pageSelectLimit_ul").hide();
                        t.$pageSelectLimitWrap.find(".pageSelectLimit_icon").css({transform: "rotate(0deg)"});
                    }
                });

            }
            /**
             * 获取数据
             * */
            , getData: function (oPageBean) {
                var t = this;
                oPageBean = oPageBean || {};
                oPageBean = $.extend(t.oPageBean, oPageBean);
                t.oPageBean = oPageBean;
                Ajax.ajax({
                    url: t.options.url
                    , type: "post"
                    , dataType: "json"
                    , contentType: "application/json;charset=UTF-8"
                    , beforeSend: function (XHR) {
                        typeof t.options.beforeSend === 'function' && t.options.beforeSend(XHR);
                    }
                    , complete: function (XHR, TS) {
                        typeof t.options.complete === 'function' && t.options.complete(XHR, TS);
                    }
                    , data: JSON.stringify($.extend({
                        pageBean: {
                            pageNo: oPageBean.pageNo + "" //传字符串
                            , pageSize: oPageBean.pageSize //每页多少条
                        }
                    }, t.options.params))
                    , success: function (data) {
                        if(data.result == "true"){
                            var params = {
                                pageBean: {
                                    pageNo: parseInt(data.pb.pageNo) || 1
                                    , pageSize: parseInt(data.pb.pageSize) || t.options.defaultLimit
                                }
                                , pb: data.pb || {}
                            };
                            t._load(params);
                            typeof t.options.success === 'function' && t.options.success(data);
                        }
                    }
                });
            }
            /**
             * 翻页数据加载处理
             * */
            , _load: function (params) {
                params = params || {pageBean: {}};
                var t = this;
                var $el = this.$el;
                var opts = this.options;


                var page = params.pageBean["pageNo"];

                var totalCount = params["pb"]["pageDataCount"] || 0;

                //如果总共0条记录就隐藏翻页控件，否则显示
                if (totalCount == 0) {
                    $el.hide();
                } else {
                    $el.show();
                }

                var limit = params.pageBean["pageSize"];
                if (!limit) {
                    limit = parseInt(this.$pageSelectLimitWrap.find("li[class='limitSelected']").text() || this.$pageSelectLimitWrap.find("li").eq(0).text()); //横向的每页条数
                }

                //选中下拉当前是每页多少条
                t.$pageSelectLimitWrap.find("li").each(function () {
                    if ($(this).text() == limit) {
                        $(this).addClass("limitSelected").siblings().removeClass("limitSelected");
                        t.$pageSelectLimitWrap.find("input.pageSelectLimit_input").val(limit);
                    }
                });

                t.totalPage = Math.ceil(totalCount / limit); //总页数
                t.$pageSelectLimitWrap.find(".pageSelectLimitTotal").html(this.formatString(opts.totalCountLabel, [totalCount])); //总记录（下拉选中每页条数旁）
                t.$positionCountLabel.html(this.formatString(opts.positionCountLabel, [page, t.totalPage])); //第x/x页
                t.$pageList.empty();

                t._plain(page, totalCount, parseInt(t.$pageSelectLimitWrap.find("li[class='limitSelected']").text() || t.$pageSelectLimitWrap.find("li").eq(0).text())); //传送参数
            }
            /**
             * 翻页按钮生成
             * */
            , _plain: function (page, totalCount, limit) {
                var t = this;
                var $el = this.$el;
                var $pageList = this.$pageList;
                var opts = this.options;
                var $positionCountLabel = this.$positionCountLabel;
                var $text = $el.find(".page_goto_text");//跳转文本框
                page = parseInt(page);

                var totalPage = totalCount % limit === 0 ? parseInt(totalCount / limit) : parseInt(totalCount / limit) + 1;
                totalPage = totalPage ? totalPage : 0;
                if (totalPage === 0) {
                    page = 1;
                } else if (page > totalPage) {
                    page = totalPage;
                } else if (page < 1 && totalPage != 0) {
                    page = 1;
                }
                //上一页
                var $prev = $('<li class="prev"><a title="上一页">&lt;</a></li>');
                if (page <= 1) {
                    $prev.addClass('disable');
                } else {
                    $prev.find('a').on('click', function () {
                        //$el.data('page', page-1);
                        t.page = page - 1;
                        $text.val("");//清空跳转文本框
                        //t.$mmGrid.load();
                        t.getData({pageNo: page - 1});
                    });
                }
                $pageList.append($prev);

                //将当前在第几页放置上一页后面
                $pageList.append($positionCountLabel);

                /////详细分页码
                if (opts.isShowPageNum) {
                    var list = [1];
                    if (page > 4) {
                        list.push('...');
                    }
                    for (var i = 0; i < 5; i++) {
                        var no = page - 2 + i;
                        if (no > 1 && no <= totalPage - 1) {
                            list.push(no);
                        }
                    }
                    if (page + 1 < totalPage - 1) {
                        list.push('...');
                    }
                    if (totalPage > 1) {
                        list.push(totalPage);
                    }
                    $.each(list, function (index, item) {
                        var $li = $('<li><a></a></li>');
                        if (item === '...') {
                            $li.addClass('dot').html('...');
                        } else if (item === page) {
                            $li.addClass('active').find('a').text(item);
                        } else {
                            $li.find('a').text(item).prop('title', '第' + item + '页').on('click', function (e) {
                                //$el.data('page', item);
                                t.page = item;
                                $text.val("");//清空跳转文本框
                                //t.$mmGrid.load();
                                t.getData({pageNo: item});
                            });
                        }
                        $pageList.append($li);
                    });
                }

                // 下一页
                var $next = $('<li class="next"><a title="下一页">&gt;</a></li>');
                if (page >= totalPage) {
                    $next.addClass('disable');
                } else {
                    $next.find('a').on('click', function () {
                        //$el.data('page', page+1);
                        t.page = page + 1;
                        $text.val("");//清空跳转文本框
                        //t.$mmGrid.load();
                        t.getData({pageNo: t.page});
                    });
                }
                $pageList.append($next);
            }
            /**
             * 字符串模板格式化
             * */
            , formatString: function (text, args) {
                return text.replace(/{(\d+)}/g, function (match, number) {
                    return typeof args[number] != 'undefined'
                        ? args[number]
                        : match
                        ;
                });
            }
            /**
             * 开始加载翻页数据
             * */
            , load: function (params) {
                params = params || {};
                var t = this;
                if (!$.isEmptyObject(params)) {
                    t.options.params = params;
                }
                t.page = 1;
                t.getData({
                    pageNo: 1
                    , pageSize: this.options.defaultLimit
                });
            }
        };

        /**
         * 把插件扩展给jQuery
         * */
        $.fn.extend({
            dayhrPaginator: function (options) {
                var oPager = new DayhrPaginator(this[0], options);
                return oPager;
            }
        });
    })(jQuery);

});